package com.shawn.integeration.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;

/**
 * @author shawn
 * @description: 并行任务处理配置
 * @date 2024/1/7
 */
//@Component
@Slf4j
public class SplitJobBathConfig {
    @Resource
    private JobBuilderFactory jobFactory;

    @Resource
    private StepBuilderFactory stepFactory;

    @Bean
    public Job splitJob() {
        return jobFactory.get("splitJob")
                .start(splitFlow1())
                .split(new SimpleAsyncTaskExecutor()).add(splitFlow2())
                .end()
                .build();
    }

    private Flow splitFlow1() {
        return new FlowBuilder<Flow>("splitFlow1")
                .start(splitStep1())
                .next(splitStep2())
                .build();
    }

    private Flow splitFlow2() {
        return new FlowBuilder<Flow>("splitFlow2")
                .start(splitStep3())
                .build();
    }

    private Step splitStep1() {
        return stepFactory.get("splitStep1")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("splitStep1执行步骤一。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    private Step splitStep2() {
        return stepFactory.get("splitStep2")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("splitStep2执行步骤二。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    private Step splitStep3() {
        return stepFactory.get("splitStep3")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("splitStep3执行步骤三。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }
}
